package com.fly.caihong.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.fly.caihong.R;
import com.fly.caihong.base.BaseActivity;
import com.fly.caihong.utils.ActivityUtils;
import com.fly.caihong.utils.ApUtils;
import com.fly.caihong.utils.AppConfig;
import com.fly.caihong.utils.DataHandler;
import com.fly.caihong.utils.DialogHelper;
import com.fly.caihong.utils.FileUtils;
import com.fly.caihong.utils.StatusBarUtils;
import com.fly.caihong.utils.ToastUtils;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class SplashActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private final int RC_PERMISSION = 0x0001;
    private final String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTransparent(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        //检查相应权限
        if (!EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            EasyPermissions.requestPermissions(this
                    , "需要外部存储写入权限"
                    , RC_PERMISSION, PERMISSIONS);
            return;
        }
        loadLocalData();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == RC_PERMISSION && perms.size() == PERMISSIONS.length) {
            loadLocalData();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ActivityUtils.finishAllActivities();
        Process.killProcess(Process.myPid());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            loadLocalData();
        }
    }

    private void loadLocalData() {
        boolean ret = FileUtils.isFileExists(AppConfig.APP_JSON_PATH);
        if (!ret) {
            showExitDialog();
            return;
        }
        boolean ret1 = DataHandler.handleAppJsonData(AppConfig.APP_JSON_PATH);
        if (!ret1) {
            showExitDialog();
            return;
        }
        launchNextActivity(100);
    }

    private void launchNextActivity(int delay) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissLoading();
                finish();
//                boolean guide = SPUtils.getInstance().getBoolean("guide", false);
//                if (!guide) {
                    ActivityUtils.startActivity(SplashActivity.this, WelcomeActivity.class);
//                } else {
//                    ActivityUtils.startActivity(SplashActivity.this, MainActivity.class);
//                }
            }
        }, delay);
    }

    private void showExitDialog() {
        DialogHelper.showDialog(this, "请检查外存储根目录下是否存在caihong子目录且包含app.json配置文件？"
                , "载入数据", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadDataOnThread();
                    }
                }, "退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ActivityUtils.finishAllActivities();
                        Process.killProcess(Process.myPid());
                    }
                });
    }

    private void loadDataOnThread() {
        showLoading("正在载入数据...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DataHandler.copyFilesFromAssets(ApUtils.getApp(), "caihong"
                            , DataHandler.EXTERNAL_STORAGE_PATH + "/caihong");
                } catch (Exception e) {
                    ToastUtils.showLong("载入失败");
                } finally {
                    SystemClock.sleep(1500);
                    DataHandler.handleAppJsonData(AppConfig.APP_JSON_PATH);
                    launchNextActivity(1000);
                }
            }
        }).start();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_splash;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.act_fade_out_anim);
    }
}
